import tkinter as tk
from tkinter import ttk
from icecream import ic
import json

# 查看配置的json数据


def populate_treeview(node, tree=None, parent=None):
    """
    Populate tree view by given json object.
    :param tree: treeview widget.
    :param parent: parent node of treeview.
    :param node: node should be a dict object.
    :return:
    """
    if tree is None:
        tree = ttk.Treeview(height=28, show='tree')
    # 如果没有父节点，建立一个父节点
    if parent is None:
        parent = tree.insert('', 'end', text='Json')

    # 由于node一定是dict，直接迭代
    ic(node)
    for item in node:
        value = node.get(item)
        if isinstance(value, dict):
            cur = tree.insert(parent, 'end', text=str(item), values=(
                str(value).replace("'", '"'), type(value).__name__))
            populate_treeview(tree=tree, parent=cur, node=value)
        elif isinstance(value, list):
            cur = tree.insert(parent, 'end', text=item, values=(
                str(value).replace("'", '"'), type(value).__name__))
            for each in value:
                if isinstance(each, dict):
                    tmp = tree.insert(cur, 'end', text='{}')
                    populate_treeview(tree=tree, parent=tmp, node=each)
                else:
                    tree.insert(cur, 'end', text=str(each), values=(
                        str(value).replace("'", '"'), type(value).__name__))
        elif isinstance(value, int) or isinstance(value, str) or isinstance(value, bool):
            tmp = str(item) + '=' + str(value)
            # tmp = str(item)
            tree.insert(parent, 'end', text=tmp, values=(
                str(value).replace("'", '"'), type(value).__name__))


def main():
    root = tk.Tk()
    tree = ttk.Treeview(root, height=28, show='tree')
    tree.pack()

    from tests.treeview_test import populate_treeview
    with open("config/app_config.json", "r", encoding='utf-8') as f:
        data = json.load(f)
        ic(data)
        populate_treeview(data, tree=tree)
        # root_config: RootConfig = RootConfig(**data)
        # g_ic_debugger(root_config)
        # populate_treeview(root_config)
    root.mainloop()


if __name__ == '__main__':
    main()
